package com.itheima.d3_tcp.no4;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 案例：实现一个简易版的BS架构
 * <p>
 * os.write("HTTP/1.1 200 ok\r\n".getBytes(StandardCharsets.UTF_8));
 * os.write("Content-Type:text/html;charset=UTF-8\r\n".getBytes(StandardCharsets.UTF_8));
 * os.write("\r\n".getBytes(StandardCharsets.UTF_8));
 * os.write("<div style='color:green;font-size:80px'>未来人人高薪就业，月薪过万！</div>".getBytes(StandardCharsets.UTF_8));
 */
public class BServerDemo04 {
    public static void main(String[] args) throws IOException {

        System.out.println("--------------服务端启动了---------------");

        //创建线程池对象
        ThreadPoolExecutor pool = new ThreadPoolExecutor(3, 5,
                2, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(8),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

        //1 创建ServerSocket镀锡，注册服务端端口号
        ServerSocket ss = new ServerSocket(8888);

        while (true) {  //循环接收客户端的连接
            //2 获取客户端的连接，只要由客户端连上就能返回socket
            Socket socket = ss.accept();  //这个方法是一个阻塞的方法，如果没有客户端连接，程序就一直卡在这。
            //只要有一个客户端连接进来了，就开启一个子线程，接收客户端发送过来的数据
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        //3 向客户端浏览器发送数据，要符合http协议数据要求
                        OutputStream os = socket.getOutputStream();
                        os.write("HTTP/1.1 200 ok\r\n".getBytes(StandardCharsets.UTF_8));
                        os.write("Content-Type:text/html;charset=UTF-8\r\n".getBytes(StandardCharsets.UTF_8));
                        os.write("\r\n".getBytes(StandardCharsets.UTF_8));
                        os.write("<div style='color:green;font-size:80px'>未来人人高薪就业，月薪过万！</div>".getBytes(StandardCharsets.UTF_8));
                        os.write(UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8));
                        //4 释放资源
                        os.close();
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

    }
}
